import { ICategoryItem, SubCategory, TopCategory } from '@/types/goods'
import { IResponse } from '@/types/data'
import request from '@/utils/request'
import { defineStore } from 'pinia'
import { topCategory } from '@/constants'

const defaultCategory = topCategory.map((item) => ({
  name: item,
}))

export default defineStore('category', {
  state: () => ({
    list: defaultCategory as ICategoryItem[], // 装分类数据的
    topCategory: {} as TopCategory,
    subCategory: {} as SubCategory,
  }),
  actions: {
    async getCategoryList() {
      const r = await request.get<IResponse<ICategoryItem[]>>('/home/category/head')
      r.data.result.forEach((item) => (item.open = false))
      this.list = r.data.result
    },
    show(categoryId: string) {
      this.list.find((item) => item.id === categoryId)!.open = true
    },
    hide(categoryId: string) {
      this.list.find((item) => item.id === categoryId)!.open = false
    },
    // 根据一级分类 ID 获取详情
    async getTopCategory(id: string) {
      const r = await request.get<IResponse<TopCategory>>('/category', {
        params: {
          id,
        },
      })
      this.topCategory = r.data.result
    },
    // 二级分类
    async getSubFilter(id: string) {
      const res = await request.get<IResponse<SubCategory>>('/category/sub/filter', {
        params: {
          id,
        },
      })
      this.subCategory = res.data.result
    },
  },
})
